package com.archie.xunji.map.tools;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.Map;

public final class HttpUtils {
	
	public static String sendByPost(String path,HashMap<String,String> params,String encode) throws IOException
	{		
		StringBuilder stringBuilder = new StringBuilder();
		for(Map.Entry<String, String> en:params.entrySet())
		{
			stringBuilder.append(en.getKey())
			             .append("=")
			             .append(URLEncoder.encode(en.getValue(),encode))
		                 .append("&");
		}
		
		stringBuilder.deleteCharAt(stringBuilder.length()-1);
		
		URL url = new URL(path);
		HttpURLConnection conn = (HttpURLConnection) url.openConnection();
		
		conn.setRequestMethod("POST");
		conn.setConnectTimeout(5000);
		conn.setDoInput(true);
		conn.setDoOutput(true);
		
		conn.setRequestProperty("Content-Type", " application/x-www-form-urlencoded");
		
		byte[] b = stringBuilder.toString().getBytes("utf-8");
		conn.setRequestProperty("Content-Length", String.valueOf(b.length));
		
		OutputStream outputStream = conn.getOutputStream();
		outputStream.write(b,0,b.length);
		outputStream.close();
		
		InputStream in = null;
		if(conn.getResponseCode()==200)
		{
			in = conn.getInputStream();
			return getResult(in,encode);
		}
		return null;
	}

	private static String getResult(InputStream in, String encode) throws IOException {
		ByteArrayOutputStream bos = new ByteArrayOutputStream();
		byte[] arr = new byte[1024];
		int len = 0;
		while((len = in.read(arr))!=-1)
		{
			bos.write(arr,0,len);
		}
		byte[] b = bos.toByteArray();
		return new String(b,encode);
	}

}
